#include "type.h"
#include "assert.h"
#include "color.h"
#include "graph.h"
#include "lcd.h"
#include "mem.h"
#include "-gui.h"
#include "dialog.h"
#include "button.h"

#define	DEFAULT_TITLE_HIGH		20
static void draw_close_button(const struct window *win)
{
	struct rect rt;
	draw_button_rect(&win->rect, ((struct button *)win->info)->status, DRAW_FILL);
	/* \ */
	rt.start_pt.x = win->rect.start_pt.x + 4;
	rt.start_pt.y = win->rect.start_pt.y + 4;
	rt.end_pt.x = win->rect.end_pt.x - 4;
	rt.end_pt.y = win->rect.end_pt.y - 4;
	lcd_draw_line(&rt, COLOR_BLACK);
	rt.start_pt.x +=1;
	rt.end_pt.x += 1;
	lcd_draw_line(&rt, COLOR_BLACK);
	/* / */
	rt.start_pt.x = win->rect.end_pt.x - 4;
	rt.start_pt.y = win->rect.start_pt.y + 4;
	rt.end_pt.x = win->rect.start_pt.x + 4;
	rt.end_pt.y = win->rect.end_pt.y - 4;
	lcd_draw_line(&rt, COLOR_BLACK);
	rt.start_pt.x -=1;
	rt.end_pt.x -= 1;
	lcd_draw_line(&rt, COLOR_BLACK);
}

void dialog_draw(const struct window *win)
{
	struct rect rt;
	struct window *ctrl;
	color_t	ft_color, bg_color;

	rt = win->rect;
	/* window outline */
	draw_button_rect(&rt, STATUS_INACTIVE, DRAW_OUTLINE);
	/* windows title bar*/
	rt.start_pt.x += 1;
	rt.start_pt.y += 1;
	rt.end_pt.x -= 1;
	rt.end_pt.y = rt.start_pt.y + DEFAULT_TITLE_HIGH;
	lcd_draw_rect(&rt, COLOR_BLUE, DRAW_FILL);
	bg_color = lcd_set_bgcolor(COLOR_BLUE);
	ft_color = lcd_set_font_color(COLOR_WHITE);
	lcd_rect_str(&rt, ((struct window_extention *)win->info)->caption, RECT_STR_LEFT);
	lcd_set_bgcolor(bg_color);
	lcd_set_font_color(ft_color);
	/* window client */
	rt.start_pt.x = win->rect.start_pt.x + 1;
	rt.start_pt.y = win->rect.start_pt.y + 1 + DEFAULT_TITLE_HIGH;
	rt.end_pt.x = win->rect.end_pt.x - 1;
	rt.end_pt.y = win->rect.end_pt.y - 1;
	lcd_draw_rect(&rt, DEFAULT_WIN_COLOR, DRAW_FILL);
	/* every ctrl */
	for (ctrl = win->child; ctrl; ctrl = ctrl->next)
		if (ctrl->draw)
			ctrl->draw(ctrl);
}

int dialog_create(struct window *win, const char *caption)
{
	struct window *ctrl;
	struct rect rt;

	win->info = (struct window_extention *)mem_alloc(sizeof(struct window_extention));
	if (!win->info)
		return 0;
	((struct window_extention *)win->info)->caption = caption;
	win->draw = dialog_draw;
	/* the close button */
	rt.start_pt.x = win->rect.end_pt.x - DEFAULT_TITLE_HIGH + 1;
	rt.start_pt.y = win->rect.start_pt.y + 1;
	ctrl = gui_create_window(win, rt.start_pt.x, rt.start_pt.y, DEFAULT_TITLE_HIGH - 2, DEFAULT_TITLE_HIGH - 2,
		WIN_BUTTON, NULL, draw_close_button, NULL);
	if (ctrl == NULL) {
		mem_free(win->info);
		return 0;
	}
	win->child = ctrl;
	return 1;
}
